<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VideoCamera, Delete, ArrowRight, Edit } from '@element-plus/icons-vue'
import { pageOrders, getOrder, updateOrder, deleteOrder } from '@/api/ticket'
import { getMovie } from '@/api/movies'
import { profile } from '@/api/user'
import dayjs from 'dayjs'

const router = useRouter()

const items = ref([])
const total = ref(0)
const pageNo = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const user = ref(null)
const movieMap = ref({})
const status = ref('') // '', 'PAID', 'UNPAID'

const detailVisible = ref(false)
const detail = ref(null)
const noteVisible = ref(false)
const noteEdit = ref('')
const noteTargetId = ref(null)

const cleanUrl = (url) => (url ? String(url).replace(/`/g, '').trim() : '')
const posterSrc = (movie) => cleanUrl(movie?.posterUrl) || cleanUrl(movie?.imageUrl) || cleanUrl(movie?.poster) || cleanUrl(movie?.cover) || ''
const fmtCurrency = (v) => {
  try { return `￥${Number(v).toFixed(2)}` } catch { return v }
}
const fmtTime = (t) => {
  try { return dayjs(t).format('YYYY-MM-DD HH:mm') } catch { return t }
}

const enrichMovies = async (records) => {
  const mids = [...new Set(records.map(r => r.mid).filter(Boolean))]
  await Promise.all(mids.map(async mid => {
    if (movieMap.value[mid]) return
    try {
      const res = await getMovie(mid)
      if (res?.code === '200') movieMap.value[mid] = res.data || {}
    } catch (e) {}
  }))
}

const loadUser = async () => {
  try {
    const res = await profile()
    if (res?.code === '200') user.value = res.data || null
  } catch {}
}

const loadPage = async () => {
  loading.value = true
  try {
    const res = await pageOrders({ pageNo: pageNo.value, pageSize: pageSize.value, status: status.value || undefined })
    if (res.code === '200') {
      items.value = res.data?.records || []
      total.value = res.data?.total || 0
      await enrichMovies(items.value)
    } else {
      ElMessage.error(res.msg || '加载订单失败')
    }
  } catch {} finally {
    loading.value = false
  }
}

onMounted(async () => {
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.info('请先登录后查看订单')
    router.push('/login')
    return
  }
  await loadUser()
  await loadPage()
})

const handleSizeChange = (size) => { pageSize.value = size; pageNo.value = 1; loadPage() }
const handlePageChange = (page) => { pageNo.value = page; loadPage() }
const handleStatusChange = () => { pageNo.value = 1; loadPage() }

const goHome = () => router.push('/')
const goMovie = (mid) => router.push(`/movie/${mid}`)

const viewDetail = async (id) => {
  try {
    const res = await getOrder(id)
    if (res.code === '200') {
      detail.value = res.data
      detailVisible.value = true
    }
  } catch {}
}

const openNoteEditor = (item) => {
  noteTargetId.value = item.id
  noteEdit.value = item.note || ''
  noteVisible.value = true
}

const saveNote = async () => {
  try {
    const res = await updateOrder({ id: noteTargetId.value, note: noteEdit.value })
    if (res.code === '200') {
      ElMessage.success('备注已更新')
      const found = items.value.find(i => i.id === noteTargetId.value)
      if (found) found.note = noteEdit.value
      noteVisible.value = false
    } else {
      ElMessage.error(res.msg || '更新失败')
    }
  } catch {}
}

const togglePaid = async (item) => {
  const target = item.status === 'PAID' ? 'UNPAID' : 'PAID'
  try {
    const res = await updateOrder({ id: item.id, status: target })
    if (res.code === '200') {
      ElMessage.success(target === 'PAID' ? '已标记为已支付' : '已标记为未支付')
      item.status = target
    } else {
      ElMessage.error(res.msg || '更新失败')
    }
  } catch {}
}

const removeOrder = async (item) => {
  try {
    await ElMessageBox.confirm(`确定删除订单 #${item.id}（《${item.mname || item.mid}》）吗？`, '提示', { type: 'warning' })
    const res = await deleteOrder(item.id)
    if (res.code === '200') {
      ElMessage.success('订单已删除')
      items.value = items.value.filter(o => o.id !== item.id)
      total.value = Math.max(0, total.value - 1)
      if (!items.value.length && total.value > 0) {
        pageNo.value = Math.max(1, pageNo.value - 1)
        loadPage()
      }
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch {}
}
</script>

<template>
  <div class="page orders" v-loading="loading">
    <!-- 顶部导航 -->
    <div class="topbar">
      <div class="brand" @click="goHome">
        <el-icon><VideoCamera /></el-icon>
        <span>我的订单</span>
      </div>
      <div class="actions">
        <el-link type="primary" @click="goHome">首页</el-link>
      </div>
    </div>

    <!-- 英雄区 -->
    <section class="hero glass">
      <h1 class="title">我的订单</h1>
      <p class="subtitle">你好，{{ (user?.nickname || user?.username || user?.uname || '影迷') }} · 共 {{ total }} 笔订单</p>
      <div class="filters">
        <el-radio-group v-model="status" @change="handleStatusChange">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button label="PAID">已支付</el-radio-button>
          <el-radio-button label="UNPAID">未支付</el-radio-button>
        </el-radio-group>
      </div>
    </section>

    <!-- 列表区 -->
    <section class="content">
      <div v-if="items.length" class="grid">
        <el-card
          v-for="o in items"
          :key="o.id"
          class="card"
          shadow="hover"
        >
          <div class="card-header">
            <h3 class="name">{{ o.mname || movieMap[o.mid]?.mname || '未知影片' }}</h3>
            <el-tag :type="o.status === 'PAID' ? 'success' : 'warning'">{{ o.status === 'PAID' ? '已支付' : '未支付' }}</el-tag>
          </div>
          <div class="card-body">
            <div class="poster-sm" v-if="posterSrc(movieMap[o.mid])">
              <img :src="posterSrc(movieMap[o.mid])" :alt="o.mname || 'poster'">
            </div>
            <div class="info">
              <div class="meta-row">
                <span class="price">{{ fmtCurrency(o.price) }}</span>
                <span class="order-id">订单编号：#{{ o.id }}</span>
              </div>
              <div class="note" v-if="o.note">备注：{{ o.note }}</div>
              <div class="time" v-if="o.createdAt">创建时间：{{ fmtTime(o.createdAt) }}</div>
            </div>
          </div>
          <div class="card-footer">
            <el-button type="primary" text @click="viewDetail(o.id)">
              查看详情
              <el-icon style="margin-left:4px"><ArrowRight /></el-icon>
            </el-button>
            <el-button text @click="goMovie(o.mid)">前往电影</el-button>
            <el-button type="warning" text @click="togglePaid(o)">
              {{ o.status === 'PAID' ? '标记未支付' : '标记已支付' }}
            </el-button>
            <el-button type="info" text @click="openNoteEditor(o)">
              编辑备注
              <el-icon style="margin-left:4px"><Edit /></el-icon>
            </el-button>
            <el-button type="danger" text @click="removeOrder(o)">
              删除订单
              <el-icon style="margin-left:4px"><Delete /></el-icon>
            </el-button>
          </div>
        </el-card>
      </div>
      <el-empty v-else description="暂无订单" />

      <div class="pager" v-if="total > 0">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :total="total"
          :page-sizes="[10,15,20]"
          :page-size="pageSize"
          :current-page="pageNo"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </section>

    <!-- 备注编辑弹窗 -->
    <el-dialog v-model="noteVisible" title="编辑备注" width="480px">
      <el-input v-model="noteEdit" type="textarea" :rows="5" placeholder="输入备注（支持富文本）" />
      <template #footer>
        <el-button @click="noteVisible=false">取消</el-button>
        <el-button type="primary" @click="saveNote">保存</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="订单详情" width="520px">
      <div v-if="detail" class="detail-box">
        <p><strong>订单编号：</strong>#{{ detail.id }}</p>
        <p><strong>影片：</strong>{{ detail.mname }}（ID: {{ detail.mid }}）</p>
        <p><strong>价格：</strong>{{ fmtCurrency(detail.price) }}</p>
        <p><strong>状态：</strong>{{ detail.status === 'PAID' ? '已支付' : '未支付' }}</p>
        <p v-if="detail.note"><strong>备注：</strong>{{ detail.note }}</p>
        <p v-if="detail.createdAt"><strong>创建时间：</strong>{{ fmtTime(detail.createdAt) }}</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="detailVisible=false">知道了</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page { min-height: 100vh; background: radial-gradient(1000px 500px at 10% 10%, rgba(99,102,241,0.15), transparent), radial-gradient(800px 400px at 90% 0%, rgba(16,185,129,0.12), transparent), #0b1020; color: #e5e7eb; }
.topbar { display: flex; align-items: center; justify-content: space-between; padding: 16px 24px; }
.brand { display: flex; align-items: center; gap: 8px; cursor: pointer; font-weight: 600; letter-spacing: 0.6px; }
.actions :deep(.el-link) { margin-left: 12px; }

.hero { margin: 16px auto 24px; padding: 20px 24px; max-width: 980px; border-radius: 16px; background: rgba(255,255,255,0.12); backdrop-filter: blur(12px); border: 1px solid rgba(255,255,255,0.22); }
.title { font-size: 24px; font-weight: 700; margin: 0 0 6px; }
.subtitle { margin: 0; color: #cfd3dc; }
.filters { margin-top: 12px; }

.content { max-width: 980px; margin: 0 auto 40px; padding: 0 12px; }
.grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 14px; }
@media (max-width: 900px) { .grid { grid-template-columns: 1fr; } }

.card { background: rgba(255,255,255,0.12); border-radius: 14px; border: 1px solid rgba(255,255,255,0.22); box-shadow: 0 6px 18px rgba(0,0,0,0.35); }
.card :deep(.el-card__body) { padding: 12px; }
.card-header { display: flex; align-items: center; justify-content: space-between; }
.name { font-weight: 600; color: #f1f5f9; }
.card-body { display: grid; grid-template-columns: 160px 1fr; gap: 12px; color: #e5e7eb; }
.poster-sm img { width: 100%; height: 160px; object-fit: cover; border-radius: 8px; display: block; }
.meta-row { display: flex; gap: 12px; align-items: center; margin-bottom: 6px; color: #dbeafe; }
.meta-row .price { display: inline-flex; align-items: center; gap: 6px; color: #a7f3d0; }
.order-id { color: #cbd5e1; }
.note { color: #e2e8f0; }
.time { color: #cbd5e1; }
.card-footer { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; padding-top: 6px; }

.pager { display: flex; justify-content: center; margin-top: 16px; }
.detail-box p { margin: 6px 0; }
</style>